package org.jeecg.modules.extbpm.process.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.extbpm.process.entity.ExtActFlowData;
import org.jeecg.modules.extbpm.process.entity.ExtActTaskNotification;
import org.jeecg.modules.extbpm.process.service.IExtActFlowDataService;
import org.jeecg.modules.extbpm.process.service.IExtActTaskNotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;

 /**
 * @Title: Controller
 * @Description: 流程表单业务表
 * @author： jeecg-boot
 * @date：   2019-03-15
 * @version： V1.0
 */
@RestController("extActFlowDataController")
@RequestMapping("/act/process/extActFlowData")
@Slf4j
public class ExtActFlowDataController {
	@Autowired
	private IExtActFlowDataService extActFlowDataService;
	@Autowired
	private IExtActTaskNotificationService extActTaskNotificationService;
	
	/**
	  * 分页列表查询
	 * @param extActFlowData
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<ExtActFlowData>> queryPageList(ExtActFlowData extActFlowData,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<ExtActFlowData>> result = new Result<IPage<ExtActFlowData>>();
		QueryWrapper<ExtActFlowData> queryWrapper = new QueryWrapper<ExtActFlowData>(extActFlowData);
		Page<ExtActFlowData> page = new Page<ExtActFlowData>(pageNo,pageSize);
		//排序逻辑 处理
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		if(oConvertUtils.isNotEmpty(column) && oConvertUtils.isNotEmpty(order)) {
			if("asc".equals(order)) {
				queryWrapper.orderByAsc(oConvertUtils.camelToUnderline(column));
			}else {
				queryWrapper.orderByDesc(oConvertUtils.camelToUnderline(column));
			}
		}
		IPage<ExtActFlowData> pageList = extActFlowDataService.page(page, queryWrapper);
		//log.debug("查询当前页："+pageList.getCurrent());
		//log.debug("查询当前页数量："+pageList.getSize());
		//log.debug("查询结果数量："+pageList.getRecords().size());
		//log.debug("数据总数："+pageList.getTotal());
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param extActFlowData
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<ExtActFlowData> add(@RequestBody ExtActFlowData extActFlowData) {
		Result<ExtActFlowData> result = new Result<ExtActFlowData>();
		try {
			extActFlowDataService.save(extActFlowData);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param extActFlowData
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<ExtActFlowData> edit(@RequestBody ExtActFlowData extActFlowData) {
		Result<ExtActFlowData> result = new Result<ExtActFlowData>();
		ExtActFlowData extActFlowDataEntity = extActFlowDataService.getById(extActFlowData.getId());
		if(extActFlowDataEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = extActFlowDataService.updateById(extActFlowData);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<ExtActFlowData> delete(@RequestParam(name="id",required=true) String id) {
		Result<ExtActFlowData> result = new Result<ExtActFlowData>();
		ExtActFlowData extActFlowData = extActFlowDataService.getById(id);
		if(extActFlowData==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = extActFlowDataService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<ExtActFlowData> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<ExtActFlowData> result = new Result<ExtActFlowData>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.extActFlowDataService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<ExtActFlowData> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ExtActFlowData> result = new Result<ExtActFlowData>();
		ExtActFlowData extActFlowData = extActFlowDataService.getById(id);
		if(extActFlowData==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(extActFlowData);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	 *	根据任务id获取流程任务流转信息
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/getProcessInfo")
	public Result<Map<String,Object>> getProcessInfo( HttpServletRequest request) {
		Result<Map<String,Object>> result = new Result<Map<String,Object>>();
		Map<String,Object> map = new HashMap<String,Object>();
		String flowCode = oConvertUtils.getString(request.getParameter("flowCode"));
		String dataId = oConvertUtils.getString(request.getParameter("dataId"));// businessKey
		LambdaQueryWrapper<ExtActFlowData> queryWrapper = new LambdaQueryWrapper<ExtActFlowData>();
		queryWrapper.eq(ExtActFlowData::getRelationCode, flowCode);
		queryWrapper.eq(ExtActFlowData::getFormDataId, dataId);
		ExtActFlowData extActFlowData = extActFlowDataService.getOne(queryWrapper);
		if(extActFlowData!=null) {
			map.put("processInstanceId",extActFlowData.getProcessInstId());
			result.setSuccess(true);
		}else {
			result.error500("数据异常！");
		}
		result.setResult(map);
		return result;
	}
	
	/**
	  * 通过flowCode formDataId查询
	 * @return
	 */
	@GetMapping(value = "/queryFlowDataByCodeAndId")
	public Result<ExtActFlowData> queryFlowDataByCodeAndId(@RequestParam(name="flowCode",required=true) String flowCode,@RequestParam(name="dataId",required=true) String dataId) {
		Result<ExtActFlowData> result = new Result<ExtActFlowData>();
		//根据流程编码和业务key查询流程实例id
		LambdaQueryWrapper<ExtActFlowData> queryWrapperD = new LambdaQueryWrapper<ExtActFlowData>();
		queryWrapperD.eq(ExtActFlowData::getRelationCode, flowCode);
		queryWrapperD.eq(ExtActFlowData::getFormDataId, dataId);
		ExtActFlowData extActFlowData = extActFlowDataService.getOne(queryWrapperD);
		if(extActFlowData==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(extActFlowData);
			result.setSuccess(true);
		}
		return result;
	}

	/**
	 * 检查业务单据办理人是否有催办提醒
	 * @param flowCode
	 * @param dataId
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/checkNotify")
	public Result<Boolean> checkNotify(@RequestParam(name="flowCode",required=true) String flowCode,
												@RequestParam(name="dataId",required=true) String dataId,
												HttpServletRequest req) {
		Result<Boolean> result = new Result<Boolean>();
		LambdaQueryWrapper<ExtActFlowData> queryWrapperD = new LambdaQueryWrapper<ExtActFlowData>();
		queryWrapperD.eq(ExtActFlowData::getRelationCode, flowCode);
		queryWrapperD.eq(ExtActFlowData::getFormDataId, dataId);
		ExtActFlowData extActFlowData = extActFlowDataService.getOne(queryWrapperD);
		
		LambdaQueryWrapper<ExtActTaskNotification> queryWrapper = new LambdaQueryWrapper<ExtActTaskNotification>();
		queryWrapper.eq(ExtActTaskNotification::getProcInstId,extActFlowData.getProcessInstId());
		String username = JwtUtil.getUserNameByToken(req);
		queryWrapper.eq(ExtActTaskNotification::getTaskAssignee, username);
		int notifyCount = extActTaskNotificationService.count(queryWrapper);
		if(notifyCount>0) {
			result.setResult(true);
		}else {
			result.setResult(false);
		}
		return result;
	}

}
